package com.qiudao.basestudy.util.result;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

/**
 * Description: 公共的返回结果
 * @author: gdc
 * @date: 2019/9/14
 * @version 1.0
 */
@ApiModel(value = "公共返回结果", description = "所有的接口公共返回值")
@Data
public class BaseResult<T> implements Serializable {
    @ApiModelProperty(value = "是否成功", required = true)
    private boolean success;
    @ApiModelProperty(value = "状态码", required = true)
    private String code;
    @ApiModelProperty(value = "状态信息")
    private String msg;
    @ApiModelProperty(value = "返回数据")
    private T data;

    /**
     * 通用返回成功
     * @return          结果
     */
    public static <T> BaseResult<T> success(){
        return new BaseResult(BaseResultEnum.SUCCESS);
    }

    /**
     * 通用返回成功
     * @param <T>       返回数据类型
     * @param t         返回数据
     * @return          结果
     */
    public static <T> BaseResult success(T t){
        BaseResult result = success();
        result.setData(t);
        return result;
    }

    /**
     * 通用返回失败
     * @return                      结果
     */
    public static BaseResult error(){
        return error(BaseResultEnum.ERROR);
    }

    /**
     * 通用返回失败
     * @return                      结果
     */
    public static BaseResult error(Exception e){
        return error(e.getMessage());
    }

    /**
     * 通用返回失败
     * @return                      结果
     */
    public static BaseResult error(String msg){
        BaseResult error = error(BaseResultEnum.ERROR);
        if (StringUtils.isNotBlank(msg)) {
            error.setMsg(msg);
        }
        return error;
    }

    /**
     * 通用返回失败
     * @param baseResultEnum        失败的枚举信息
     * @return                      结果
     */
    public static BaseResult error(BaseResultEnum baseResultEnum){
        return new BaseResult(baseResultEnum);
    }

    private BaseResult(BaseResultEnum baseResultEnum){
        this.success = baseResultEnum.isSuccess();
        this.code = baseResultEnum.getCode();
        this.msg = baseResultEnum.getMsg();
    }

}
